#!/usr/bin/python3

import yaml
import socket
import sys
import os
import getopt

def printUsage():
    print('Generate crypto-config.yaml\nUsage:')
    print('    gen_crypto_config.py -o <orderer_num> -p <peer_num> -t <template_count> -u <user_count>')
    print('    or: gen_crypto_config.py --orderer_num=<orderer_num> --peer_num=<peer_num> --template_count=<template_count> --user_count=<user_count>')
 
def parseArgs(argv):
    orderer_num = 1
    peer_num = 4
    template_count = 1
    user_count = 1
    opts, args = getopt.getopt(argv[1:], "ho:p:t:u:", ["help", "orderer_num=", "peer_num=", "template_count=", "user_count="])

    if len(opts) > 4 or len(args) != 0:
        print('Invalid paramater')
        sys.exit()
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            printUsage()
            sys.exit()
        elif opt in ("-o", "--orderer_num"):
            orderer_num = int(arg)
        elif opt in ("-p", "--peer_num"):
            peer_num = int(arg)
        elif opt in ("-t", "--template_count"):
            template_count = int(arg)
        elif opt in ("-u", "--user_count"):
            user_count = int(arg)
    return (orderer_num, peer_num, template_count, user_count)

def generate_orderer_config(orderer_num):
    orderer_config = {
        "OrdererOrgs": [
            {
                "Name": "Orderer",
                "Domain": "demo.com",
                "EnableNodeOUs": True,
                "Specs": [{"Hostname": f"orderer{i}"} for i in range(1, orderer_num + 1)]
            }
        ]
    }
    return orderer_config

def generate_peer_config(peer_num, template_count, user_count):
    peer_config = {"PeerOrgs": []}

    for i in range(1, peer_num + 1):
        org_data = {
            "Name": f"Org{i}",
            "Domain": f"org{i}.demo.com",
            "EnableNodeOUs": True,
            "Template": {"Count": template_count},
            "Users": {"Count": user_count}
        }
        peer_config["PeerOrgs"].append(org_data)

    return peer_config

if __name__ == "__main__":
    orderer_num, peer_num, template_count, user_count = parseArgs(sys.argv)
    # print(orderer_num, peer_num, template_count)
    
    crypto_config = {}

    orderer_config = generate_orderer_config(orderer_num)
    crypto_config.update(orderer_config)
    peer_config = generate_peer_config(peer_num, template_count, user_count)
    crypto_config.update(peer_config)
    # print(yaml.dump(crypto_config, default_flow_style=False, allow_unicode=True))

    with open('crypto-config.yaml', 'w', encoding='utf8') as f:
        yaml.dump(crypto_config, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
